var resourceCtrl  = new XFApp.client();
var chart_data = "";
XFApp.client.prototype.resource = {
    successCode : "10000",
    page : null,
    urlItems : {
        queryDataURL : basePath+"/statistic/getStatisticData",
        dataToExcelURL : basePath+"/statistic/dataToExcel"
    },
    setChart: function(result){
        var myChart = echarts.init(document.getElementById('main'));
        //--- 折柱 ---
       // 参数设置，参考http://echarts.baidu.com/doc/option.html
        var colors = ['#5793f3', '#d14a61', '#675bba'];
        //legend 统计项目的名称
        var legend = new Array();
        //xAxis x轴坐标内容
        var xAxisData = new Array();
        //总重，总包裹数，总价值
        var totalWeight = 0,totalCount = 0,totalPrice = 0;
        var weightArr = new Array();var countArr = new Array();var priceArr = new Array();
        var charts = result.charts;
        for(var i = 0; i < charts.length; i ++){
            legend.push(charts[i].name);
            var chartsData = charts[i].data;
            for(var k = 0; k < chartsData.length; k ++){
                if(charts[i].name == '重量') {
                    totalWeight += chartsData[k].num;
                    weightArr.push(chartsData[k].num);
                    xAxisData.push(chartsData[k].date);
                };
                if(charts[i].name == '包裹数') {
                    totalCount += chartsData[k].num;
                    countArr.push(chartsData[k].num);
                };
                if(charts[i].name == '货物价值') {
                    totalPrice += chartsData[k].num;
                    priceArr.push(chartsData[k].num);
                };
            }
        }
        this.setCountUp("packageCount",totalCount);
        this.setCountUp("packagePrice",totalPrice);
        this.setCountUp("packageWeight",totalWeight);
        var option = {
            color: colors,

            tooltip: {
                trigger: 'axis'
            },
            grid: {
                right: '20%'
            },
            toolbox: {
                feature: {
                    dataView: {show: true, readOnly: false},
                    restore: {show: true}
                    //saveAsImage: {show: true}
                }
            },
            legend: {
                data:legend,
                y: 'bottom'
            },
            xAxis: [
                {
                    type: 'category',
                    axisTick: {
                        alignWithLabel: true
                    },
                    data: xAxisData
                }
            ],
            yAxis: [
                {
                    type: 'value',
                    name: '重量',
                    position: 'right',
                    axisLine: {
                        lineStyle: {
                            color: colors[0]
                        }
                    },
                    axisLabel: {
                        formatter: '{value} （千克）'
                    }
                },
                {
                    type: 'value',
                    name: '包裹数',
                    position: 'right',
                    offset: 80,
                    axisLine: {
                        lineStyle: {
                            color: colors[1]
                        }
                    },
                    axisLabel: {
                        formatter: '{value} （个）'
                    }
                },
                {
                    type: 'value',
                    name: '货物价值',
                    position: 'left',
                    axisLine: {
                        lineStyle: {
                            color: colors[2]
                        }
                    },
                    axisLabel: {
                        formatter: '{value} （美元）'
                    }
                }
            ],
            series: [
                {
                    name:'重量',
                    type:'bar',
                    data:weightArr
                },
                {
                    name:'包裹数',
                    type:'bar',
                    yAxisIndex: 1,
                    data:countArr
                },
                {
                    name:'货物价值',
                    type:'line',
                    yAxisIndex: 2,
                    data:priceArr
                }
            ]
        };
        
        //myChart.setTheme('dark');
        myChart.setOption(option);
    },
    setPie: function (pie){
        var top1 = echarts.init(document.getElementById('top1'));
        var top2 = echarts.init(document.getElementById('top2'));
        var legend1 = new Array();
        var legend2 = new Array();
        var data1 = pie.topClass;
        var data2 = pie.topPrice;
        for(var i = 0; i < data1.length; i ++){
            legend1.push(data1[i].name);
        }
        for(var i = 0; i < data2.length; i ++){
            legend2.push(data2[i].name);
        }
        var option1 = {
            title: {
                text: 'top10商品出口',
                x:'right'
            },
            tooltip: {
                trigger: 'item',
                formatter: "{a} <br/>{b}: {c} ({d}%)"
            },
            legend: {
                orient: 'vertical',
                x: 'left',
                data:legend1
            },
            series: [
                {
                    name:'top10商品出口',
                    type:'pie',
                    radius: ['50%', '70%'],
                    avoidLabelOverlap: false,
                    label: {
                        normal: {
                            show: false,
                            position: 'center'
                        },
                        emphasis: {
                            show: true,
                            textStyle: {
                                fontSize: '30',
                                fontWeight: 'bold'
                            }
                        }
                    },
                    labelLine: {
                        normal: {
                            show: false
                        }
                    },
                    data:data1
                }
            ]
        };
        var option2 = {
            title: {
                text: 'top10品类销售金额（USD）',
                x:'right'
            },
            tooltip: {
                trigger: 'item',
                formatter: "{a} <br/>{b}: {c} ({d}%)"
            },
            legend: {
                orient: 'vertical',
                x: 'left',
                data:legend2
            },
            series: [
                {
                    name:'top10品类销售金额（USD）',
                    type:'pie',
                    radius: ['50%', '70%'],
                    avoidLabelOverlap: false,
                    label: {
                        normal: {
                            show: false,
                            position: 'center'
                        },
                        emphasis: {
                            show: true,
                            textStyle: {
                                fontSize: '30',
                                fontWeight: 'bold'
                            }
                        }
                    },
                    labelLine: {
                        normal: {
                            show: false
                        }
                    },
                    data:data2
                }
            ]
        };
        top1.setOption(option1);
        top2.setOption(option2);
    },
    setCountUp: function(elId,count){
        var options = {
          useEasing : true, 
          useGrouping : true, 
          separator : ',', 
          decimal : '.', 
          prefix : '', 
          suffix : '' 
        };
        var targetEle = document.getElementById(elId);
        var up = new CountUp(targetEle, 0, count, 0, 2.5, options);
        up.start();
    },
    chart : function(){
        var _this = this;
        _this.loadingDialog = webDialogUtil.loading('正在加载数据，请稍后...');
        $.ajax({
            url:_this.urlItems.queryDataURL,
            data:{
                reqTimeStart:$("[name='reqTimeStart']").val(),
                reqTimeEnd:$("[name='reqTimeEnd']").val()
            },
            type:'get',
            cache:false,
            dataType:'json',
            success:function(data) {
                if(true == data.isSuccess){
                    var result = data.result;
                    _this.setChart(result);
                    _this.setPie(result.pie);
                    _this.loadingDialog.close();
                    chart_data = data.fileName;
                }
            },
            error : function() {
            	_this.loadingDialog.close();
                window.webDialogUtil.alert("提示","操作失败");
            }
        });
    },
	ajaxDownload : function(fileName){
		var _this = this;
		var url = _this.urlItems.dataToExcelURL+"?fileName=" + fileName;
		$("body").append("<iframe id='file_download_frame' src='" + url +"' frameborder=0 width=0 height=0 style='display:none'></iframe>");
	},    
    event : function(){
        _this = this;
		$("#exportButton").on("click",function(){
			resourceCtrl.resource.ajaxDownload(chart_data);
		});

        $("#searchButton").on("click",function(){
            _this.chart();
        });
    }
};
$(function(){
    resourceCtrl.resource.chart();
    resourceCtrl.resource.event();
});